package org.ws.httphelper.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PropertyUtil {

    private static Logger log = LoggerFactory.getLogger(PropertyUtil.class.getName());

    public static Field[] getFields(Class clazz){
        Field[] fields = clazz.getDeclaredFields();
        Map<String, Field> getMethodNames = new HashMap<>();
        for (Field field : fields) {
            getMethodNames.put("get"+field.getName().toLowerCase(),field);
            getMethodNames.put("is"+field.getName().toLowerCase(),field);
        }
        List<Field> list = new ArrayList<>();
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            String key = method.getName().toLowerCase();
            if(getMethodNames.containsKey(key)){
                list.add(getMethodNames.get(key));
            }
        }
        Class superClass = clazz.getSuperclass();
        if(!superClass.equals(Object.class)){
            list.addAll(Arrays.asList(getFields(superClass)));
        }

        return list.toArray(new Field[list.size()]);
    }

    public static Object getValue(Object input,String fieldName){
        Class<?> inClass = input.getClass();
        try {
            PropertyDescriptor descriptor = new PropertyDescriptor(fieldName, inClass);
            return descriptor.getReadMethod().invoke(input);
        } catch (Exception e) {
            log.error("get field value error:{}",e.getMessage());
            return null;
        }
    }

}
